/* Copyright (c) 2010, Peter Lényi */
/* Licensed under The BSD License. */

package gem.apps.fs.web;

import gem.apps.fs.entities.FileMeta;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet class FileUploadmetaPostServlet validates data in the form and
 * forwards metadata to next form.
 *
 * @author Peter Lényi
 * @version 20100426F
 */
public class FileUploadmetaPostServlet extends HttpServlet
{
    private static final String ADDRESS_FATAL = "/error/fatal/jsp";
    private static final String ADDRESS_WARNING = "/file/uploadmeta/jsp";
    private static final String ADDRESS_SUCCESS = "/file/uploadfile/jsp";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // prepare local variables
        boolean validationError = false;
        List<String> messages = new ArrayList<String>();

        // prepare resources
        ResourceBundle gui = ResourceBundle.getBundle("Gui");

        // load request parameters
        String title = request.getParameter("form.title");
        String comment = request.getParameter("form.comment");
        String owner = request.getParameter("form.owner");
        String password = request.getParameter("form.password");

        // validate data
        if (title == null || title.equals("")) {
            messages.add(gui.getString("Gui.form.file.title.err"));
            validationError = true;
        }
        if (comment == null) {
            comment = "";
        }
        if (owner == null || owner.equals("")) {
            messages.add(gui.getString("Gui.form.file.owner.err"));
            validationError = true;
        }
        if (password == null) {
            password = "";
        }

        // execute logic
        FileMeta meta = new FileMeta();
        meta.setTitle(title);
        meta.setComment(comment);
        meta.setOwner(owner);
        meta.setPassword(password);

        request.getSession().setAttribute("msg", messages);
        // pass connection
        if (!validationError) {
            request.getSession().setAttribute("filemeta", meta);
            response.sendRedirect(getServletContext().getContextPath() + ADDRESS_SUCCESS);
        }
        else {
            response.sendRedirect(getServletContext().getContextPath() + ADDRESS_WARNING);
        }
    }
}
